package com.woniuxy.ribbon.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ribbon的配置类，不要被IOC直接扫描
 * @return
 */
public class WeightRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private NacosServiceManager nacosServiceManager;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    /**
     * 选择实例节点
     * @param o
     * @return
     */
    @Override
    public Server choose(Object o) {
        //1.获取当前请求需要访问的服务ID
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();
        String name = baseLoadBalancer.getName();//product-service
        //2.获取当前节点的注册信息
        String group = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        //3.获取nacos的服务发现对象
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        //4.调用服务发现对象的方法来获取相关组一级相关集群的节点
        List<Instance> instances=null;
        try {
            instances = namingService.selectInstances(name, group,true);
        } catch (NacosException e) {
            try {
                namingService.selectInstances(name,"DEFAULT_GROUP",true);
            } catch (NacosException ex) {
                ex.printStackTrace();
            }
        }
        List<Instance> clusterInsances = null;
        if (instances!=null&&instances.size()>0){
            clusterInsances = instances.stream().filter(instance -> instance.getClusterName().equals(clusterName)).collect(Collectors.toList());
            if (clusterInsances==null||clusterInsances.size()<=0) clusterInsances=instances;
        }
        //5.在剩下的节点中通过权重算法选一个
        if (clusterInsances!=null&&clusterInsances.size()>0){
            Instance instance = MyWeightUtil.getRandomWeight(clusterInsances);
            //5.得到服务返回
            return new NacosServer(instance);
        }
        return null;
    }

    static class MyWeightUtil extends Balancer{
        public static Instance getRandomWeight(List<Instance> hosts){
            return Balancer.getHostByRandomWeight(hosts);
        }
    }
}
